package com.ljh.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static com.ljh.nio.c1.ByteBufferUtil.debugAll;

/**
 * @author: Themberfue
 * @date: 2025/5/26 22:26
 * @description:
 */
@Slf4j
public class AIOFileChannel {
    public static void main(String[] args) throws IOException {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("data.txt"), StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.debug("read begin...");
            /**
             * ByteBuffer
             * position
             * attachment
             * 回调对象
             */
            channel.read(buffer, 0, buffer, new CompletionHandler<>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read complete... {}", result);
                    attachment.flip();
                    debugAll(attachment);
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.debug("read end...");
        // ! 由于默认开启的是守护进程，守护进程随着主进程结束而结束，故需让主进程等一会
        System.in.read();
    }
}
